package com.wmz.springCloud.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.wmz.springCloud.common.CommonResult;
import com.wmz.springCloud.entity.Payment;
import com.wmz.springCloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/customer")
public class CustomerController {

    private final String PRIVATE_NAME = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancer loadBalancer;

    @GetMapping("/getById/{id}")
    public CommonResult<Payment> getById(@PathVariable Long id) {
        return restTemplate.getForObject(PRIVATE_NAME + "/payment/getPaymentById/" + id, CommonResult.class);
    }

    @GetMapping("/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(PRIVATE_NAME + "/payment/create/",payment, CommonResult.class);
    }

    @GetMapping("/getByIdEntity/{id}")
    public CommonResult<Payment> getByIdEntity(@PathVariable Long id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PRIVATE_NAME + "/payment/getPaymentById/" + id, CommonResult.class);

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(dto -> {
            log.info(dto.getHost() + dto.getPort());
        });

        if (forEntity.getStatusCode().is2xxSuccessful()) {
            return forEntity.getBody();
        }
        return null;
    }

    @GetMapping("/getIdByMyLb/{id}")
    public CommonResult<Payment> getIdByMyLb(@PathVariable Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (CollectionUtil.isNotEmpty(instances)) {
            ServiceInstance instance = loadBalancer.instances(instances);
            return restTemplate.getForObject(instance.getUri() + "/payment/getPaymentById/" + id,CommonResult.class);
        }
        return null;
    }
}
